package com.lj.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.common.core.model.TreeSelect;
import com.lj.common.core.model.system.SysDept;
import com.lj.system.mapper.SysDeptMapper;
import com.lj.system.service.ISysDeptService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统配置服务实现类
 *
 * @author 小李飞刀
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    /**
     * 构建前端所需要下拉树结构
     *
     * @param deptList 部门列表
     * @return 部门下拉列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> deptList) {
        List<SysDept> deptTrees = buildDeptTree(deptList);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<SysDept> buildDeptTree(List<SysDept> deptList) {
        // 父级ID是 0 的为顶级部门
        List<SysDept> topDeptList = deptList.stream().filter(dept -> dept.getParentId().intValue() == 0).collect(Collectors.toList());
        // 将顶级部门过滤掉
        List<SysDept> subDeptList = deptList.stream().filter(dept -> dept.getParentId().intValue() != 0).collect(Collectors.toList());
        topDeptList.forEach(dept -> recursionFn(subDeptList, dept));
        if (CollUtil.isEmpty(topDeptList)) {
            topDeptList = deptList;
        }
        return topDeptList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept pDept) {
        // 得到子节点列表
        List<SysDept> childList = list.stream().filter(item -> item.getParentId().intValue() == pDept.getDeptId().intValue()).collect(Collectors.toList());
        pDept.setChildren(childList);
        for (SysDept tChild : childList) {
            if (list.stream().filter(item -> item.getParentId().intValue() == tChild.getDeptId().intValue()).count() > 0L) {
                recursionFn(list, tChild);
            }
        }
    }
}
